package com.wlyuan.open.domain.source.service.impl;

import com.alibaba.fastjson.JSON;
import com.wlyuan.core.exception.AssertUtils;
import com.wlyuan.finance.api.IBillRecordService;
import com.wlyuan.finance.api.IBillService;
import com.wlyuan.open.domain.source.assembler.BillAssembler;
import com.wlyuan.open.domain.source.assembler.PayAssembler;
import com.wlyuan.open.domain.source.service.IOpenFinanceService;
import com.wlyuan.open.dto.OpenBillSyncDTO;
import com.wlyuan.open.dto.OpenPaySyncDTO;
import com.wlyuan.open.infrastructure.exception.SourceValueErrorException;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

/**
 * @author yuanzheng
 */
@Service
@Slf4j
@RequiredArgsConstructor
@Data
public class OpenFinanceServiceImpl implements IOpenFinanceService {
    @DubboReference(check = false, timeout = 60000, retries = 0)
    private final IBillService billService;
    @DubboReference(check = false, timeout = 60000, retries = 0)
    private final IBillRecordService billRecordService;

    @Override
    public Long sync(OpenBillSyncDTO source) {
        var creation = BillAssembler.assemble(source);
        logger.info("请求创建对账单:{},{}", source.getSourceKey(), JSON.toJSON(creation));
        var bill = billService.rewrite(creation);
        AssertUtils.assertNotNull(bill, new SourceValueErrorException("创建对账单失败"), source);
        return bill;
    }

    @Override
    public Long sync(OpenPaySyncDTO source) {
        var creation = PayAssembler.assemble(source);
        logger.info("请求创建收付款：{},{}", source.getSourceKey(), JSON.toJSON(creation));
        var bill = billRecordService.rewrite(creation);
        AssertUtils.assertNotNull(bill, new SourceValueErrorException("创建收付款失败"), source);
        return bill;
    }

}
